from lib.server.http import response
from lib.server.http.fs import net_fs
from utils import device,format
from lib.config.index import server_config

async def api_handle_reboot(writer, path):
    await response.return_json_ok(writer)
    await writer.drain()
    device.reboot()

async def api_handle_projects(writer, path):
    projects = net_fs.__projects
    res = {"projects": projects, "current": net_fs.__current_project["name"]}
    if server_config.is_debug():
        print("config projects:", res)
    await response.return_json_data(writer, res)

async def api_handle_change_project(writer, path):
    name = format.get_search_params(path, "name")
    if server_config.is_debug():
        print("http server change project to: ", name)
    if name:
        net_fs.set_current_project(name)
    else:
        net_fs.set_current_project("default")
    await response.return_json_ok(writer)

async def api_handle_led_on(writer, path):
    from lib.board.index import led
    led.on()
    await response.return_json_ok(writer)

async def api_handle_lef_off(writer, path):
    from lib.board.index import led

    led.off()
    await response.return_json_ok(writer)

async def api_handle_device_id(writer, path):
    device_id = device.get_id()
    res = {"value": device_id}
    await response.return_json_data(writer, res)

async def api_handle_device_info(writer, path):
    from lib.config.index import get_all_configs

    info = {"device_info": device.get_info()}
    configs = get_all_configs()
    info.update(configs)
    await response.return_json_data(writer, info)

async def api_handle_config(writer, path):
    from lib.config.index import get_all_configs
    configs = get_all_configs()
    await response.return_json_data(writer, configs)

api_routes = {
    "/reboot": api_handle_reboot,
    "/projects": api_handle_projects,
    "/change_project": api_handle_change_project,
    "/led_on": api_handle_led_on,
    "/led_off": api_handle_lef_off,
    "/device_id": api_handle_device_id,
    "/device_info": api_handle_device_info,
    "/info": api_handle_device_info,
    "/config": api_handle_config,
}


async def handle_api_routes(writer, path):
    (prefix, path) = path.split('/api')
    key = path.split('?')[0]
    if key in api_routes:
        handler = api_routes[key]
        await handler(writer, path)

    await writer.drain()
